package com.project.filter;

import com.project.util.Request;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@Order(1)
@WebFilter(filterName = "csrfFilter", urlPatterns = "/*")
public class CsrfFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain
    ) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getMethod().equals("POST")) {
            String csrfFromSession = (String) request.getSession().getAttribute("X-CSRF-TOKEN");
            String csrfToken = null;
            if (Request.isAjax(request)) {
                csrfToken = request.getHeader("X-CSRF-TOKEN");
            } else {
                csrfToken = request.getParameter("csrfToken");
            }

            if (csrfToken == null) {
                throw new ServletException("csrf mistake,please check your csrfToken");
            }
            if (!csrfToken.equals(csrfFromSession)) {
                throw new ServletException("csrf mistake,please check your csrfToken");
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
